﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using Facade;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.SalesOneWeb
{
    public class SOSecurityPage : SOBasePage
    {
        StructureFacade facade;

        internal StringCollection ValidateUserCredentials(string url)
        {
            if (Request.ApplicationPath.Length > 1 && url.Contains(Request.ApplicationPath))
                url = url.Substring(Request.ApplicationPath.Length);

            facade = new StructureFacade();
            StringCollection credentialList = new StringCollection();

            if (User.Identity.IsAuthenticated)
            {
                credentialList = getAllCredentials(facade.GetUserCredentials(User.Identity.Name, url));
                if (credentialList.Count > 0)
                {
                    if (string.IsNullOrEmpty(Request.QueryString["a"]) || (credentialList.Contains(Request.QueryString["a"])))
                    {
                        return credentialList;
                    }
                }
            }
            else
            {
                Response.Redirect("~/Login.aspx");
            }

            if (Request.UrlReferrer.ToString() != null)
                Response.Redirect(Request.UrlReferrer.ToString());
            else
                Response.Redirect("~/index.aspx");
            
            return credentialList;
        }

        private StringCollection getAllCredentials(List<TaskCredentials> list)
        {
            StringCollection collection = new StringCollection();
            foreach (TaskCredentials rolePermission in list)
            {
                foreach (string cred in rolePermission.Credentials.Split(','))
                {
                    if (!collection.Contains(cred))
                        collection.Add(cred);
                }
            }
            return collection;
        }

    }
}
